<template>
  <div class="video-detail" v-loading="loading">
    <!-- 视频播放区域 -->
    <el-card class="video-player-card">
      <div class="video-player-container">
        <video
          ref="videoPlayer"
          class="video-player"
          :src="videoInfo.videoUrl"
          :poster="videoInfo.coverUrl"
          controls
          @timeupdate="handleTimeUpdate"
          @ended="handleVideoEnded"
        ></video>
      </div>
      
      <div class="video-info">
        <h1 class="video-title">{{ videoInfo.title }}</h1>
        <div class="video-meta">
          <span><i class="el-icon-view"></i> {{ videoInfo.views }} 次观看</span>
          <span><i class="el-icon-date"></i> {{ formatDate(videoInfo.uploadTime) }}</span>
          <span><i class="el-icon-time"></i> {{ formatDuration(videoInfo.duration) }}</span>
        </div>
        
        <div class="video-actions">
          <el-button
            icon="el-icon-star-off"
            :type="isCollected ? 'warning' : ''"
            @click="toggleCollection"
          >
            {{ isCollected ? '取消收藏' : '收藏' }}
          </el-button>
          <el-button icon="el-icon-share">分享</el-button>
          <el-button icon="el-icon-document" @click="downloadNotes" v-if="videoInfo.hasNotes">下载笔记</el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 视频详情和评论 -->
    <el-card class="video-content-card">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="视频简介" name="intro">
          <div class="video-author">
            <el-avatar :size="50" :src="videoInfo.authorAvatar"></el-avatar>
            <div class="author-info">
              <h3>{{ videoInfo.author }}</h3>
              <p>{{ videoInfo.authorTitle }}</p>
            </div>
          </div>
          
          <div class="video-description" v-html="videoInfo.description"></div>
          
          <div class="video-chapters" v-if="videoInfo.chapters && videoInfo.chapters.length > 0">
            <h3>课程章节</h3>
            <el-collapse accordion>
              <el-collapse-item 
                v-for="(chapter, index) in videoInfo.chapters" 
                :key="index"
                :title="chapter.title"
                :name="index"
              >
                <div class="chapter-content">
                  <p>{{ chapter.description }}</p>
                  <div class="chapter-timestamp">
                    <el-button type="text" @click="seekToTime(chapter.timestamp)">
                      跳转至 {{ formatDuration(chapter.timestamp) }}
                    </el-button>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="用户评价" name="comments">
          <div class="comments-section">
            <div class="comment-form">
              <h3>发表评价</h3>
              <el-rate v-model="newComment.rating" show-text></el-rate>
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入您对此视频的评价..."
                v-model="newComment.content">
              </el-input>
              <div class="form-actions">
                <el-button type="primary" @click="submitComment">提交评价</el-button>
              </div>
            </div>
            
            <div class="comment-list">
              <h3>全部评价 ({{ comments.length }})</h3>
              <el-empty v-if="comments.length === 0" description="暂无评价"></el-empty>
              
              <div v-for="(comment, index) in comments" :key="index" class="comment-item">
                <div class="comment-header">
                  <div class="user-info">
                    <el-avatar :size="40" :src="comment.avatar"></el-avatar>
                    <span class="username">{{ comment.username }}</span>
                  </div>
                  <div class="comment-rating">
                    <el-rate v-model="comment.rating" disabled></el-rate>
                    <span class="comment-time">{{ formatDate(comment.time) }}</span>
                  </div>
                </div>
                <div class="comment-content">{{ comment.content }}</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="学习笔记" name="notes">
          <div class="notes-section">
            <div class="notes-form">
              <h3>添加笔记</h3>
              <div class="timestamp-input">
                <span>时间点: {{ formatDuration(currentTime) }}</span>
                <el-button size="small" type="primary" @click="captureCurrentTime">使用当前时间</el-button>
              </div>
              <el-input
                type="textarea"
                :rows="3"
                placeholder="在此添加笔记内容..."
                v-model="newNote.content">
              </el-input>
              <div class="form-actions">
                <el-button type="primary" @click="addNote">保存笔记</el-button>
              </div>
            </div>
            
            <div class="notes-list">
              <h3>我的笔记</h3>
              <el-empty v-if="notes.length === 0" description="暂无笔记"></el-empty>
              
              <div v-for="(note, index) in notes" :key="index" class="note-item">
                <div class="note-header">
                  <div class="timestamp">
                    <el-button type="text" @click="seekToTime(note.timestamp)">
                      {{ formatDuration(note.timestamp) }}
                    </el-button>
                  </div>
                  <div class="note-actions">
                    <el-button type="text" icon="el-icon-edit" @click="editNote(index)"></el-button>
                    <el-button type="text" icon="el-icon-delete" @click="deleteNote(index)"></el-button>
                  </div>
                </div>
                <div class="note-content">{{ note.content }}</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 相关视频推荐 -->
    <el-card class="related-videos-card">
      <div slot="header">
        <span>相关视频推荐</span>
      </div>
      
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="(video, index) in relatedVideos" :key="index">
          <el-card class="video-card" shadow="hover" @click.native="goToDetail(video.id)">
            <div class="video-cover">
              <img :src="video.coverUrl" :alt="video.title">
              <div class="video-duration">{{ formatDuration(video.duration) }}</div>
              <div class="play-icon">
                <i class="el-icon-video-play"></i>
              </div>
            </div>
            <div class="video-info">
              <h3 class="video-title">{{ video.title }}</h3>
              <div class="video-meta">
                <span><i class="el-icon-user"></i> {{ video.author }}</span>
                <span><i class="el-icon-view"></i> {{ video.views }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'VideoDetail',
  
  data() {
    return {
      loading: true,
      videoId: null,
      videoInfo: {
        title: '',
        videoUrl: '',
        coverUrl: '',
        author: '',
        authorAvatar: '',
        authorTitle: '',
        views: 0,
        uploadTime: '',
        duration: 0,
        description: '',
        hasNotes: false,
        chapters: []
      },
      activeTab: 'intro',
      isCollected: false,
      comments: [],
      relatedVideos: [],
      currentTime: 0,
      notes: [],
      newComment: {
        rating: 5,
        content: ''
      },
      newNote: {
        timestamp: 0,
        content: ''
      },
      editingNoteIndex: -1
    }
  },
  
  created() {
    this.videoId = this.$route.params.id
    this.fetchVideoDetail()
    this.fetchComments()
    this.fetchRelatedVideos()
    this.fetchNotes()
  },
  
  methods: {
    async fetchVideoDetail() {
      try {
        this.loading = true
        // 这里替换为实际的API调用
        // const response = await this.$api.video.getVideoDetail(this.videoId)
        // const videoUrlResponse = await this.$api.video.getVideoUrl(this.videoId)
        
        // 模拟数据
        setTimeout(() => {
          this.videoInfo = {
            title: 'JavaScript高级编程技巧 - 异步编程与Promise',
            videoUrl: 'https://www.w3schools.com/html/mov_bbb.mp4', // 示例视频URL
            coverUrl: 'https://via.placeholder.com/800x450?text=JavaScript',
            author: '张老师',
            authorAvatar: 'https://via.placeholder.com/50',
            authorTitle: '高级前端工程师 | 编程讲师',
            views: 2568,
            uploadTime: '2023-05-15',
            duration: 1800, // 30分钟
            description: `<p>本视频详细讲解了JavaScript中的异步编程技巧，包括以下内容：</p>
            <ul>
              <li>异步编程基础概念</li>
              <li>回调函数及其问题</li>
              <li>Promise的使用方法</li>
              <li>async/await语法糖</li>
              <li>实际项目中的应用案例</li>
            </ul>
            <p>适合有一定JavaScript基础的学生学习提高。</p>`,
            hasNotes: true,
            chapters: [
              {
                title: '第1章: 异步编程基础',
                description: '介绍JavaScript中的异步编程概念和基础知识',
                timestamp: 0
              },
              {
                title: '第2章: 回调函数',
                description: '讲解回调函数的使用方法和回调地狱问题',
                timestamp: 300
              },
              {
                title: '第3章: Promise详解',
                description: '深入讲解Promise的创建、链式调用和错误处理',
                timestamp: 720
              },
              {
                title: '第4章: async/await',
                description: '使用async/await简化异步代码',
                timestamp: 1200
              },
              {
                title: '第5章: 实战案例',
                description: '通过实际项目案例应用所学知识',
                timestamp: 1500
              }
            ]
          }
          
          this.loading = false
        }, 500)
      } catch (error) {
        this.$message.error('获取视频详情失败')
        this.loading = false
      }
    },
    
    async fetchComments() {
      try {
        // 这里替换为实际的API调用
        // const response = await this.$api.video.getComments(this.videoId)
        
        // 模拟数据
        setTimeout(() => {
          this.comments = [
            {
              username: '学生A',
              avatar: 'https://via.placeholder.com/40',
              rating: 5,
              content: '讲解非常清晰，特别是Promise部分的例子很实用，帮我解决了项目中的问题。',
              time: '2023-06-10'
            },
            {
              username: '学生B',
              avatar: 'https://via.placeholder.com/40',
              rating: 4,
              content: '内容很好，但是async/await部分讲解有点快，希望能有更多的例子。',
              time: '2023-06-08'
            },
            {
              username: '学生C',
              avatar: 'https://via.placeholder.com/40',
              rating: 5,
              content: '老师讲解的很透彻，我终于理解了Promise的工作原理。',
              time: '2023-06-05'
            }
          ]
        }, 300)
      } catch (error) {
        this.$message.error('获取评论失败')
      }
    },
    
    async fetchRelatedVideos() {
      try {
        // 这里替换为实际的API调用
        // const response = await this.$api.video.getRelatedVideos(this.videoId)
        
        // 模拟数据
        setTimeout(() => {
          this.relatedVideos = [
            {
              id: 7,
              title: 'JavaScript ES6新特性详解',
              coverUrl: 'https://via.placeholder.com/300x200?text=ES6',
              author: '张老师',
              views: 1586,
              duration: 1500 // 秒
            },
            {
              id: 8,
              title: 'Vue.js前端开发入门',
              coverUrl: 'https://via.placeholder.com/300x200?text=Vue.js',
              author: '李老师',
              views: 2310,
              duration: 2400 // 秒
            },
            {
              id: 9,
              title: 'React Hooks完全指南',
              coverUrl: 'https://via.placeholder.com/300x200?text=React',
              author: '王老师',
              views: 1875,
              duration: 1800 // 秒
            },
            {
              id: 10,
              title: '前端性能优化实战',
              coverUrl: 'https://via.placeholder.com/300x200?text=Performance',
              author: '赵老师',
              views: 1432,
              duration: 2100 // 秒
            }
          ]
        }, 300)
      } catch (error) {
        this.$message.error('获取相关视频失败')
      }
    },
    
    async fetchNotes() {
      try {
        // 这里替换为实际的API调用
        // const response = await this.$api.video.getNotes(this.videoId)
        
        // 模拟数据
        setTimeout(() => {
          this.notes = [
            {
              timestamp: 125,
              content: '异步编程的核心概念：非阻塞执行'
            },
            {
              timestamp: 450,
              content: '回调地狱的问题：嵌套过深、错误处理困难、代码可读性差'
            },
            {
              timestamp: 840,
              content: 'Promise.all() 可以并行执行多个异步操作，提高效率'
            }
          ]
        }, 300)
      } catch (error) {
        this.$message.error('获取笔记失败')
      }
    },
    
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    
    formatDuration(seconds) {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = Math.floor(seconds % 60)
      return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
    },
    
    handleTimeUpdate() {
      if (this.$refs.videoPlayer) {
        this.currentTime = this.$refs.videoPlayer.currentTime
        
        // 这里可以添加记录观看进度的逻辑
        // 例如每30秒保存一次进度
        if (Math.floor(this.currentTime) % 30 === 0 && this.currentTime > 0) {
          this.saveWatchProgress()
        }
      }
    },
    
    handleVideoEnded() {
      // 视频播放结束的处理逻辑
      this.$message.success('视频播放完成')
      this.saveWatchProgress(true)
    },
    
    async saveWatchProgress(completed = false) {
      try {
        // 这里替换为实际的API调用
        // await this.$api.video.updateWatchProgress(this.videoId, {
        //   progress: this.currentTime,
        //   completed: completed
        // })
      } catch (error) {
        console.error('保存观看进度失败', error)
      }
    },
    
    seekToTime(timestamp) {
      if (this.$refs.videoPlayer) {
        this.$refs.videoPlayer.currentTime = timestamp
        if (this.$refs.videoPlayer.paused) {
          this.$refs.videoPlayer.play()
        }
      }
    },
    
    toggleCollection() {
      this.isCollected = !this.isCollected
      this.$message.success(this.isCollected ? '收藏成功' : '已取消收藏')
      
      // 这里替换为实际的API调用
      // await this.$api.video.toggleCollection(this.videoId, this.isCollected)
    },
    
    downloadNotes() {
      this.$message.success('笔记下载中...')
      // 这里替换为实际的下载逻辑
    },
    
    submitComment() {
      if (!this.newComment.content) {
        this.$message.warning('请输入评价内容')
        return
      }
      
      // 这里替换为实际的API调用
      // await this.$api.video.submitComment(this.videoId, this.newComment)
      
      this.comments.unshift({
        username: '我',
        avatar: this.$store.getters.avatar || 'https://via.placeholder.com/40',
        rating: this.newComment.rating,
        content: this.newComment.content,
        time: new Date().toISOString().split('T')[0]
      })
      
      this.$message.success('评价提交成功')
      this.newComment.content = ''
      this.newComment.rating = 5
    },
    
    captureCurrentTime() {
      this.newNote.timestamp = this.currentTime
    },
    
    addNote() {
      if (!this.newNote.content) {
        this.$message.warning('请输入笔记内容')
        return
      }
      
      if (this.editingNoteIndex >= 0) {
        // 编辑现有笔记
        this.notes[this.editingNoteIndex] = {
          timestamp: this.newNote.timestamp,
          content: this.newNote.content
        }
        this.editingNoteIndex = -1
      } else {
        // 添加新笔记
        this.notes.push({
          timestamp: this.newNote.timestamp,
          content: this.newNote.content
        })
      }
      
      // 按时间戳排序
      this.notes.sort((a, b) => a.timestamp - b.timestamp)
      
      // 这里替换为实际的API调用
      // await this.$api.video.saveNotes(this.videoId, this.notes)
      
      this.$message.success('笔记保存成功')
      this.newNote.content = ''
      this.newNote.timestamp = this.currentTime
    },
    
    editNote(index) {
      this.editingNoteIndex = index
      this.newNote.timestamp = this.notes[index].timestamp
      this.newNote.content = this.notes[index].content
      this.activeTab = 'notes'
    },
    
    deleteNote(index) {
      this.$confirm('确定删除该笔记吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.notes.splice(index, 1)
        
        // 这里替换为实际的API调用
        // await this.$api.video.saveNotes(this.videoId, this.notes)
        
        this.$message.success('笔记删除成功')
      }).catch(() => {
        // 取消删除
      })
    },
    
    goToDetail(id) {
      if (id === parseInt(this.videoId)) return
      this.$router.push(`/video-center/${id}`)
    }
  }
}
</script>

<style lang="scss" scoped>
.video-detail {
  padding: 20px;
  
  .video-player-card {
    margin-bottom: 20px;
    
    .video-player-container {
      width: 100%;
      background-color: #000;
      
      .video-player {
        width: 100%;
        max-height: 600px;
      }
    }
    
    .video-info {
      padding: 20px;
      
      .video-title {
        margin: 0 0 15px;
        font-size: 24px;
      }
      
      .video-meta {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 20px;
        color: #606266;
        
        span {
          margin-right: 20px;
          
          i {
            margin-right: 5px;
          }
        }
      }
      
      .video-actions {
        .el-button {
          margin-right: 10px;
        }
      }
    }
  }
  
  .video-content-card {
    margin-bottom: 20px;
    
    .video-author {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 20px;
      border-bottom: 1px solid #ebeef5;
      
      .author-info {
        margin-left: 15px;
        
        h3 {
          margin: 0 0 5px;
        }
        
        p {
          margin: 0;
          color: #606266;
          font-size: 14px;
        }
      }
    }
    
    .video-description {
      margin-bottom: 30px;
      line-height: 1.6;
      
      ul {
        padding-left: 20px;
        
        li {
          margin-bottom: 8px;
        }
      }
    }
    
    .video-chapters {
      h3 {
        margin-bottom: 15px;
      }
      
      .chapter-content {
        p {
          margin-top: 0;
        }
        
        .chapter-timestamp {
          text-align: right;
        }
      }
    }
    
    .comments-section, .notes-section {
      padding: 20px;
      
      .comment-form, .notes-form {
        margin-bottom: 30px;
        
        h3 {
          margin-bottom: 15px;
        }
        
        .el-rate {
          margin-bottom: 15px;
        }
        
        .el-input {
          margin-bottom: 15px;
        }
        
        .timestamp-input {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;
        }
      }
      
      .comment-list, .notes-list {
        h3 {
          margin-bottom: 20px;
        }
        
        .comment-item, .note-item {
          margin-bottom: 20px;
          padding-bottom: 20px;
          border-bottom: 1px solid #ebeef5;
          
          &:last-child {
            border-bottom: none;
          }
          
          .comment-header, .note-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            
            .user-info {
              display: flex;
              align-items: center;
              
              .username {
                margin-left: 10px;
                font-weight: bold;
              }
            }
            
            .comment-rating {
              display: flex;
              flex-direction: column;
              align-items: flex-end;
              
              .comment-time {
                margin-top: 5px;
                font-size: 12px;
                color: #909399;
              }
            }
          }
          
          .comment-content, .note-content {
            line-height: 1.6;
          }
        }
      }
    }
  }
  
  .related-videos-card {
    .video-card {
      margin-bottom: 20px;
      cursor: pointer;
      transition: transform 0.3s;
      
      &:hover {
        transform: translateY(-5px);
        
        .play-icon {
          opacity: 1;
        }
      }
      
      .video-cover {
        position: relative;
        height: 150px;
        overflow: hidden;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .video-duration {
          position: absolute;
          bottom: 10px;
          right: 10px;
          padding: 2px 8px;
          background-color: rgba(0, 0, 0, 0.6);
          color: #fff;
          border-radius: 4px;
          font-size: 12px;
        }
        
        .play-icon {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: rgba(0, 0, 0, 0.3);
          opacity: 0;
          transition: opacity 0.3s;
          
          i {
            font-size: 48px;
            color: #fff;
          }
        }
      }
      
      .video-info {
        padding: 10px;
        
        .video-title {
          margin: 0 0 10px;
          font-size: 16px;
          height: 44px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .video-meta {
          display: flex;
          justify-content: space-between;
          color: #909399;
          font-size: 13px;
          
          i {
            margin-right: 4px;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .video-detail {
    .video-player-card {
      .video-info {
        .video-meta {
          flex-direction: column;
          gap: 5px;
        }
        
        .video-actions {
          margin-top: 15px;
          
          .el-button {
            margin-bottom: 10px;
          }
        }
      }
    }
  }
}
</style> 